import 'package:flutter/material.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_logic.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';

import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/sound/sound_manager.dart';
import 'package:flutter_09_game/utils/utils_image.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:qr_flutter/qr_flutter.dart';

class GameDetailTransferLogic extends BaseController {
  // 投注金额控制器
  TextEditingController amountController = TextEditingController();

  ScrollController scrollController = ScrollController();

  // 倒计时
  RxString countdown = '00:30'.obs;

  RxBool selectOddRx = false.obs;

  List<String> symbols =
      AppUserManager().walletList.map((f) => f.symbol ?? '').toList();
  late RxString symbolRx = symbols.isNotEmpty ? symbols.first.obs : ''.obs;

  List<int> inputs = [20, 100, 500, 1000, 5000];

  RxBool canPlaceBetRx = false.obs;

  final GlobalKey _repaintBoundaryKey = GlobalKey();

  @override
  void onReady() {
    super.onReady();
    _startCountdown();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToEnd();
    });
    ever(Get.find<GameDetailLogic>().gameRoundRx, (value) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToEnd();
      });
    });
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    amountController.addListener(textControllerListener);

    // 初始化音效管理器
    SoundManager().initialize();
  }

//  Assets.gameVolumeClose,
  textControllerListener() {
    // 播放按键音效
    if (Get.find<GameDetailLogic>().soundRx.value) {
      SoundManager().playButtonSound();
    }

    canPlaceBetRx.value = amountController.text.isNotEmpty;
  }

  @override
  void onClose() {
    amountController.dispose();
    // coinController.dispose();
    super.onClose();
    scrollController.dispose();
  }

  /// 开始倒计时
  void _startCountdown() {
    // 模拟倒计时，实际应该从服务器获取
    int seconds = 30;
    Future.doWhile(() async {
      await Future.delayed(Duration(seconds: 1));
      seconds--;
      if (seconds >= 0) {
        int minutes = seconds ~/ 60;
        int remainingSeconds = seconds % 60;
        countdown.value =
            '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
        return true;
      } else {
        // 倒计时结束，重新开始
        seconds = 30;
        return true;
      }
    });
  }

  /// 滚动到最右边
  void _scrollToEnd() {
    if (scrollController.hasClients) {
      scrollController.animateTo(
        scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  postGameRoundJoin() async {
    GameDetailLogic gameLogic = Get.find<GameDetailLogic>();
    HttpResponse response = await HttpManager().post(
      API.postGameRoundJoin,
      // fromJson: .fromJson,
      params: {
        'amount': (int.tryParse(amountController.text) ?? 0) * 1000000,
        'symbol': symbolRx.value,
        'game_id': gameLogic.gameId,
        'round': gameLogic.rightHistoryRx.value?.round,
        'direction': selectOddRx.value ? 2 : 1,
      },
    );

    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.betSuccess.tr);
      amountController.text = '';
    }
  }

  showScanQr() {
    CommonNormalSheet(
      title:
          "【${Get.find<GameDetailLogic>().name}】${LocaleKeys.betAddressQrCode.tr}",
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Column(
          children: [
            RepaintBoundary(
                key: _repaintBoundaryKey,
                child: Container(
                  color: AppColor.pageBgColor,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    children: [
                      Text(
                        LocaleKeys.betUseWalletTip.tr,
                        style: TextStyle(
                          color: AppColor.primary,
                          fontSize: 12.sp,
                        ),
                      ),
                      24.verticalSpaceFromWidth,
                      ClipRRect(
                        borderRadius: BorderRadius.circular(12.w),
                        child: QrImageView(
                          data: Get.find<GameDetailLogic>().getReceiveAddress(),
                          version: QrVersions.auto,
                          size: 156.w,
                          padding: EdgeInsets.all(10.w),
                          backgroundColor: Colors.white,
                        ),
                      ),
                      24.verticalSpaceFromWidth,
                    ],
                  ),
                )),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.w)
                  .copyWith(right: 6.w),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                borderRadius: BorderRadius.circular(8.w),
              ),
              child: Row(
                children: [
                  Expanded(
                      child: Text(
                    Get.find<GameDetailLogic>().getReceiveAddress(),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: AppColor.textPrimary.withOpacity(0.94),
                      fontSize: 14.sp,
                      // fontWeight: FontWeight.w600
                    ),
                  )),
                  8.horizontalSpace,
                  GestureDetector(
                    onTap: () {
                      UtilsOther.copyMemberId(
                          Get.find<GameDetailLogic>().getReceiveAddress());
                    },
                    child: AutoImage(
                      Assets.gameCopy,
                      width: 32.w,
                    ),
                  )
                ],
              ),
            ),
            24.verticalSpaceFromWidth,
            CommonButton.expend(
              title: LocaleKeys.saveQrCode.tr,
              onClick: () {
                UtilImage.saveImageToGallery(_repaintBoundaryKey);
              },
            )
          ],
        ),
      ),
    ).show();
  }
}
